import { defineStore } from "pinia";
import request from '@/utils/request'
import { CartItem } from '@/types/cart'
import { ApiResObj } from '@/types/data'
import useStore from "..";
const useCartStore = defineStore('cart', {
  // 状态
  state: () => ({
    // 购物车列表
    list: [] as CartItem[],
  }),
  persist: {
    key: 'rabbit-cart-list-ma'
  },
  // 计算
  getters: {
    //商品列表中的商品有isEffectie:true表示有效商品false表示无效
    // stock>0 表示有库存 小于0 表示没有库存
    //筛选出有效商品和 库存不为零时
    effectiveList(): CartItem[] {
      return this.list.filter(item => item.isEffective && item.stock > 0)
    },
    //总数
    allCounts(): number {
      // let all = 0
      // this.effectiveList.forEach(item => {
      //   all += item.count
      // })
      return this.effectiveList.reduce((sum, item) => sum + item.count, 0)
    },
    //总价
    allPrice(): string {
      const price = this.effectiveList.reduce((sum, item) => sum + item.count * +item.nowPrice, 0)
      return price.toFixed(2)
    },
    //计算全选按钮是否选中
    isAllSelected(): boolean {
      return this.effectiveList.length > 0 && this.effectiveList.every(item => item.selected)
    },
    //已选商品
    selectedGoods(): CartItem[] {
      return this.effectiveList.filter(item => item.selected)
    },
    //已选商品数量
    selectedCounts(): number {
      return this.selectedGoods.reduce((sum, item) => sum + item.count, 0)
    },
    //已选商品总价
    selectedPrice(): string {
      return this.selectedGoods.reduce((sum, item) => sum + (+item.nowPrice * item.count), 0).toFixed(2)
    },
    //判断登录状态
    isLogin(): boolean {
      const { user } = useStore()
      // return user.profile.token ? true : false
      return Boolean(user.profile.token)
      // return !!user.profile.token
    }
  },
  // 方法
  actions: {
    //添加购物车
    async addCart(data: CartItem) {
      if (this.isLogin) {
        await request.post('/member/cart', { skuId: data.skuId, count: data.count })
        this.getCartList()
      } else {
        // console.log('本地操作');
        const goods = this.list.find(item => item.skuId === data.skuId)
        if (goods) {
          goods.count += data.count
        } else {
          this.list.unshift(data)
        }
      }
    },
    //获取购物车列表
    async getCartList() {
      if (this.isLogin) {
        const res = await request.get<ApiResObj<CartItem[]>>('/member/cart')
        this.list = res.data.result
      } else {
        type Resitem = {
          isEffective: boolean
          nowPrice: string
          stock: number
        }
        // 发送一次请求获取一下本地数据
        this.list.forEach(async item => {
          const res = await request.get<ApiResObj<Resitem>>(`/goods/stock/${item.skuId}`)
          console.log(res);
          item.isEffective = res.data.result.isEffective
          item.nowPrice = res.data.result.nowPrice
          item.stock = res.data.result.stock
        })
      }
    },
    //删除购物车商品
    async delCart(ids: string[]) {
      //params 查询参数 会将参数 地址后 ？参数
      // delete 请求也可也传请求体
      // await request.delete('/menber/cart', { params: { id } })
      if (this.isLogin) {
        await request.delete('/member/cart', { data: { ids } })
        this.getCartList()
      } else {
        // console.log('本地操作');
        // this.list.filter(item => item.skuId !== ids[0])
        this.list = this.effectiveList.filter(item => !ids.includes(item.skuId))
      }
    },
    // 修改购物车商品（状态和数量）
    async updateCart(skuid: string, data: { selected?: boolean, count?: number }) {
      if (this.isLogin) {
        const res = await request.put(`/member/cart/${skuid}`, data)
        console.log(res);
        // 重新获取购物车列表
        this.getCartList()
      } else {
        //  console.log('本地');
        const goods = this.effectiveList.find(item => item.skuId === skuid)
        // 如果修改状态为false 那么永远不会进这个分支
        if (data.selected !== undefined) {
          goods!.selected = data.selected
        }
        if (data.count !== undefined) {
          goods!.count = data.count
        }
      }
    },
    //全选和反选
    async changeAllSelected(selected: boolean) {
      if (this.isLogin) {
        await request.put('/member/cart/selected', { selected })
        this.getCartList()
      } else {
        // console.log('本地');
        this.list.forEach(item => item.selected = selected)
      }
    },
    //退出清空购物车
    //被async修饰过的函数 即便没有返回值 也有返回值 返回的是一个promise
    //在vuex中 actions中写的函数不管有没有加async 返回值都说promise
    clearCart() {
      this.list = []
    },
    //登录后合并购物车 本地的同步到用户的
    async mergeCart() {
      const newArr = this.list.map(item => {
        return {
          skuId: item.skuId,
          selected: item.selected,
          count: item.count
        }
      })
      await request.post('/member/cart/merge',newArr)
      this.getCartList()
    }
  },
});

export default useCartStore;